package com.kfm.servlet.cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;

@WebServlet("/time")
public class TimeServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf8");

        // 先获取上一次访问时间
        Cookie[] cookies = req.getCookies();
        boolean isFirst = true;
        for (Cookie cookie : cookies){
            if ("lastTime".equals(cookie.getName())){
                String value = cookie.getValue();
                resp.getWriter().write("上一次访问时间为：" + value);
                isFirst = false;
            }
        }

        if (isFirst){
            resp.getWriter().write("这是您第一次访问本站");
        }
        // 把当前时间存入cookie
        Cookie cookie = new Cookie("lastTime", LocalDateTime.now().toString());
        cookie.setMaxAge(60 * 60 * 24 * 30);
        resp.addCookie(cookie);
    }
}
